package com.sakura.oj.sandbox.controller;

import com.sakura.oj.sandbox.CodeSandbox;
import com.sakura.oj.sandbox.model.ExecuteCodeRequest;
import com.sakura.oj.sandbox.model.ExecuteCodeResponse;
import com.sakura.oj.sandbox.template.CodeSandboxFactory;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

/**
 * 代码沙箱控制器
 */
@Slf4j
@RestController
@RequestMapping("/sandbox")
public class SandboxController {

    @Resource
    private CodeSandboxFactory sandboxFactory;
    
    /**
     * 执行代码
     *
     * @param executeCodeRequest 执行代码请求
     * @return 执行结果 {@link ExecuteCodeResponse}
     */
    @PostMapping("/execute")
    public ExecuteCodeResponse executeCode(@RequestBody ExecuteCodeRequest executeCodeRequest) {
        try {
            log.info("收到代码执行请求，语言：{}", executeCodeRequest.getLanguage());
            
            // 使用工厂获取合适的沙箱实现
            CodeSandbox sandbox = sandboxFactory.getSandbox(executeCodeRequest);
            
            // 执行代码
            return sandbox.executeCode(executeCodeRequest);
        } catch (Exception e) {
            log.error("代码执行异常", e);
            
            // 处理异常情况
            ExecuteCodeResponse errorResponse = new ExecuteCodeResponse();
            errorResponse.setStatus(500);
            errorResponse.setMessage("系统错误：" + e.getMessage());
            return errorResponse;
        }
    }
    
    /**
     * 指定模式执行代码
     *
     * @param mode              运行模式 (docker/native)
     * @param executeCodeRequest 执行代码请求
     * @return 执行结果
     */
    @PostMapping("/execute/{mode}")
    public ExecuteCodeResponse executeCodeWithMode(
            @PathVariable("mode") String mode,
            @RequestBody ExecuteCodeRequest executeCodeRequest) {
        try {
            log.info("收到代码执行请求，语言：{}，模式：{}", executeCodeRequest.getLanguage(), mode);
            
            // 使用工厂获取指定模式的沙箱实现
            CodeSandbox sandbox = sandboxFactory.getSandbox(executeCodeRequest.getLanguage(), mode);
            
            // 执行代码
            return sandbox.executeCode(executeCodeRequest);
        } catch (Exception e) {
            log.error("代码执行异常", e);
            
            // 处理异常情况
            ExecuteCodeResponse errorResponse = new ExecuteCodeResponse();
            errorResponse.setStatus(500);
            errorResponse.setMessage("系统错误：" + e.getMessage());
            return errorResponse;
        }
    }
} 